package com.ykq.sso.realm;

import com.ykq.pojo.entity.User;
import com.ykq.sso.feign.PermissionFeign;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @program: qy151-springboot-shiro
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-05 11:14
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private PermissionFeign permissionFeign;

    //什么时候执行该方法: 当你进行权限校验时会执行该方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    //认证代码
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登录账号
        String username = authenticationToken.getPrincipal().toString();

        //2.根据账号查询用户信息--远程调用权限微服务接口
        User user = permissionFeign.findByUsername(username);

        //3.判断用户是否存在
        if(user!=null){
            //4.判断密码是否正确
            ByteSource salt=ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
            return info;
        }
        return null;
    }
}
